package com.jiankangjin.alipaychannel.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiankangjin.alipaychannel.alipay.util.AlipayNotify;
import com.jiankangjin.httpclient.HttpClient;

@Controller
public class NotifyController {
	private static final transient Log logger = LogFactory.getLog(NotifyController.class);

	Map<String, String> params = new HashMap<String, String>();
	
	/**
	 * 服务器异步通知 支付宝对商户的请求数据处理完成后，会将处理的结果数据通过服务器主动通知的
	 * 方式通知给商户网站。这些处理结果数据就是服务器异步通知参数。
	 */
	@RequestMapping(value = "/notify", method = RequestMethod.POST)
	@ResponseBody
	public String acceptNotify(HttpServletRequest request) {
		Map<?, ?> requestParams = request.getParameterMap();
		for (Iterator<?> iter = requestParams.keySet().iterator(); iter
				.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			params.put(name, valueStr);
		}

		logger.info(this +"收到支付宝通知参数:" + params);
		if (AlipayNotify.verify(params)) {
			logger.info("验证成功");
			if ("trade_status_sync".equals(params.get("notify_type"))) {
				String out_trade_no = params.get("out_trade_no");
				String trade_no = params.get("trade_no");
				String trade_status = params.get("trade_status");
				logger.info("trade_status_sync 支付记录号:" + out_trade_no + " 交易号:" + trade_no + " 交易状态:" + trade_status);
				String trade_state = "0000";
				String trade_time = (String)params.get("gmt_payment");
//				String buyer_id = (String)params.get("buyer_id");
				String buyer_email = (String)params.get("buyer_email");
//				String seller_id = (String)params.get("seller_id");
				String seller_email = (String)params.get("seller_email");
				String total_fee = (String)params.get("total_fee");
				total_fee = String.valueOf(Math.round(Double.parseDouble(total_fee) * 100.0D));
				
				if (trade_status.equals("WAIT_BUYER_PAY")) {
					trade_state = "0021";
					logger.info("isWAIT_BUYER_PAY 支付宝等待用户输入密码确定此支付");
				} else if (trade_status.equals("TRADE_CLOSED")) {
					trade_state = "0071";
					logger.info("isTRADE_CLOSED 用户支付超时,或者支付已经全部退款");
				} else if (trade_status.equals("TRADE_SUCCESS")) {
					trade_state = "1001";
					logger.info("isTRADE_SUCCESS 用户支付的时候免密支付成功,或输入密码后,支付成功");
				} else if (trade_status.equals("TRADE_PENDING")) {
					trade_state = "0021";
					logger.info("isTRADE_PENDING 用户已付款,卖家未收到款.");
				} else if (trade_status.equals("TRADE_FINISHED")) {
					trade_state = "1001";
					logger.info("isTRADE_FINISHED 交易成功且结束，即不可再做任何操作 ");
				}
				//通知交易系统
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("notify_type", "pay_sync");
				params.put("out_trade_no", out_trade_no);
				params.put("order_id", "");
				params.put("pay_cry", "156");
				params.put("pay_amt", total_fee);
				params.put("pay_chnl_seq", trade_no);
				params.put("pay_fin_time", convertTime(trade_time));
				params.put("Pay_chnl_pos", "");
				params.put("Pay_chnl_mer", seller_email);
				params.put("Pay_chnl_fee", "");
				params.put("pay_user", buyer_email);
				params.put("sub_deal_status", trade_state);
				params.put("sub_deal_msg", "交易成功");
				logger.info("通知交易系统：" + params);
				Map<String, Object> returnMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/channel_notify", params);
				logger.info("通知交易系统返回：" + returnMap);
				if("0000".equals(returnMap.get("resp_status"))) {
					logger.info("通知交易系统成功");
					return "success";
				}
			} else {
				logger.error("通知类型 notify_type="+params.get("notify_type")+"未知,无法处理");
			}
		} else {
			logger.error("验证失败");
		}
		return "fail";
	}
	
	private String convertTime(String timestr) {
		String str = timestr.replace("-", "");
		str = str.replace(" ", "");
		str = str.replace(":", "");
		return str;
	}
}
/* 取到的参数例子:
 * buyer_email=15197293693
 * &buyer_id=2088502645921769
 * &gmt_create=2014-08-14 10:45:44
 * &gmt_payment=2014-08-14 10:45:45
 * &notify_action_type=payByAccountAction
 * &notify_id=2fc15de689df825ee2fae22db87cd87lv4
 * &notify_time=2014-08-14 10:45:46
 * &notify_type=trade_status_sync
 * &out_trade_no=0123456789
 * &paytools_pay_amount=[{"BANKCARD":"0.01"}]
 * &price=0.01
 * &quantity=1
 * &seller_email=guodayaofangzy@qq.com
 * &seller_id=2088311338307490
 * &sign=cHSpYLiegh/gtzd16pEpNw6qpvR37mLOJyh96sBtgoq9YqjXejfPSJZ2+MUAEvRPowCzDFNDD1J9cSMcSzuRsULEGfhCJGWjbaTKfEnCbumdnrtko0a9q128w5dd67Qw66kjWbT8sMqkUKwwpDSLR9Sf0dJlN0RxDVC3L5pkJko=
 * &sign_type=RSA
 * &subject=barcode_pay_test
 * &total_fee=0.01
 * &trade_no=2014081421001004760010863554
 * &trade_status=TRADE_SUCCESS
 */
